package cadc.actions;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;

import com.itextpdf.text.BadElementException;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.pdf.PdfWriter;
import com.windpicker.common.utils.Encoder;

@SuppressWarnings("serial")
public class Baoming extends UserAction {
	private String biao;
	private int size;
	private InputStream inputStream;
	
	public String execute(){
		try {
			byte[] biaoByte = Encoder.decryptBASE64(biao);
			byte[] pdfByte = toPdf(biaoByte);
			setSize(pdfByte.length);
			setInputStream(new ByteArrayInputStream(pdfByte));
		} catch (IOException e) {
			e.printStackTrace();
		}
		return SUCCESS;
	}
	
	private byte[] toPdf(byte[] data){
		Document document = new Document(PageSize.A4_LANDSCAPE, 0, 0, 0, 0);
		PdfWriter writer=null;
		ByteArrayOutputStream pdf = new ByteArrayOutputStream();
		try {
			writer = PdfWriter.getInstance(document, pdf);
		} catch (DocumentException e1) {
			e1.printStackTrace();
		}
		writer.setCompressionLevel(0);
		document.open();
		Image img = null;
		try {
			img = Image.getInstance(data);
		} catch (BadElementException e) {
			e.printStackTrace();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		img.scaleAbsolute(595, 842);
		img.setAbsolutePosition((PageSize.A4_LANDSCAPE.getWidth() - img.getScaledWidth()) / 2,
            (PageSize.A4_LANDSCAPE.getHeight() - img.getScaledHeight()) / 2);
		try {
			writer.getDirectContent().addImage(img);
		} catch (DocumentException e) {
			e.printStackTrace();
		}
		document.close();
		return pdf.toByteArray();
	}
	
	public void setBiao(String biao) {
		this.biao = biao;
	}
	public String getBiao() {
		return biao;
	}
	public void setSize(int size) {
		this.size = size;
	}
	public int getSize() {
		return size;
	}
	public void setInputStream(InputStream inputStream) {
		this.inputStream = inputStream;
	}
	public InputStream getInputStream() {
		return inputStream;
	}
}
